import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { Params } from '@angular/router';
import { AfMessageService, AfNavigationService, AfDateService } from '@core';
import { differenceInCalendarDays } from 'date-fns';
import { NzMessageService } from 'ng-zorro-antd/message';
import { TransferItem } from 'ng-zorro-antd/transfer';

import { SecurityService } from '../../security.service';

@Component({
  selector: 'app-security-user-edit',
  styleUrls: ['./edit.component.less'],
  templateUrl: './edit.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SecurityUserEditComponent implements OnInit {
  form!: UntypedFormGroup;
  submitting = false;
  saveError = null;

  constructor(
    private fb: UntypedFormBuilder,
    private msg: NzMessageService,
    private securitySrv: SecurityService,
    private cdr: ChangeDetectorRef,
    private msgSrv: AfMessageService,
    private navSrv: AfNavigationService,
    private dateSrv: AfDateService
  ) {}

  editParam!: Params;
  record: any;
  btn: any = 'add';
  ngOnInit(): void {
    this.form = this.fb.group({
      id: ['', []],
      username: ['', [Validators.required]],
      nickName: ['', [Validators.required]],
      phone: ['', [Validators.required, Validators.pattern(/^1\d{10}$/), Validators.minLength(11), Validators.maxLength(11)]],
      employeeId: ['', []],
      email: ['', [Validators.email]],
      password: ['', [Validators.minLength(3)]],
      accountNonLocked: [true, []],
      disabled: [false, []]
    });

    this.initFormValue();
    this.queryUserRole(this.form.controls['id'].value);
    this.queryDataPermission(this.form.controls['username'].value);
    this.cdr.detectChanges();
  }

  selectedIndex = 0;
  treeTitle: any = '分配角色';
  initFormValue() {
    this.editParam = this.navSrv.getQueryParam();
    this.btn = this.editParam['btn'];
    this.selectedIndex = this.editParam['index'];
    if (this.btn == 'edit') {
      this.record = JSON.parse(this.editParam['record']);
      // console.log(JSON.stringify(this.record));
      this.treeTitle = `为“${this.record.username}”分配角色`;
      this.form.patchValue(this.record);
    }
  }

  submit(): void {
    const body = this.form.getRawValue();

    this.submitting = true;
    this.securitySrv.saveUser(body).subscribe(res => {
      if (res.status) {
        this.form.controls['id'].setValue(res.data);
        this.treeTitle = `为“${this.form.controls['username'].value}”分配角色`;

        this.msgSrv.msg_success(`提交成功`);
      } else {
        this.msgSrv.msg_warning(`${res.msg}`);
      }
    });

    setTimeout(() => {
      this.submitting = false;
      this.cdr.detectChanges();
    }, 1000);
  }

  today = new Date();
  disabledDate = (current: Date): boolean => {
    return differenceInCalendarDays(current, this.today) < 0;
  };

  back() {
    this.navSrv.navigateByUrl('/security/user/list');
  }

  translist: TransferItem[] = [];
  userRoles: any[] = [];
  queryUserRole(userId: any) {
    this.securitySrv.queryUserRole(userId).subscribe(res => {
      if (res.status) {
        this.userRoles = res.data;
        this.translist = [];
        if (this.userRoles.length >= 1) {
          this.userRoles.forEach(item => {
            this.translist.push({
              id: item.roleId,
              title: `${item.name} -- ${item.descr}`,
              disabled: item.disabled,
              direction: item.allocated ? 'right' : 'left'
            });
          });
        }
        this.cdr.detectChanges();
      } else {
        this.msgSrv.msg_error(res.msg);
      }
    });
  }

  grantRole() {
    if (this.form.controls['id'].value == null || this.form.controls['id'].value == '') {
      this.msgSrv.msg_error('请先提交用户后，才能提交分配角色');
      return;
    }
    const selectItem: TransferItem[] = this.translist.filter(item => item.direction == 'right');
    console.log('grantRole', selectItem);
    if (!selectItem || selectItem.length <= 0) {
      this.msgSrv.msg_error('请选择角色');
      return;
    }
    const roleIds = selectItem.map((item: any) => item.id);

    this.securitySrv.saveUserRole(this.record.id, roleIds).subscribe(res => {
      if (res.status) {
        this.msgSrv.msg_success('角色分配成功');
      } else {
        this.msgSrv.msg_error(res.msg);
      }
    });
  }

  phoneDecrypted = false;
  queryDataPermission(username: any) {
    if (this.form.controls['id'].value == null || this.form.controls['id'].value == '') {
      this.phoneDecrypted = false;
      return;
    }

    this.securitySrv.queryDataPermission(username).subscribe(res => {
      if (res.status) {
        if (res.data) {
          this.phoneDecrypted = res.data.phoneDecrypted;
          this.cdr.detectChanges();
        }
      } else {
        this.msgSrv.msg_error(res.msg);
      }
    });
  }

  savePhoneDecrypted() {
    if (this.form.controls['id'].value == null || this.form.controls['id'].value == '') {
      this.msgSrv.msg_error('请先提交用户后，才能提交分配角色');
      return;
    }

    this.securitySrv.saveDataPermission(this.form.controls['username'].value, this.phoneDecrypted).subscribe(res => {
      if (res.status) {
        this.msgSrv.msg_success('设置数据权限成功');
      } else {
        this.msgSrv.msg_error(res.msg);
      }
    });
  }
}
